﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TCPAndUDPWin
{
    public partial class TCPWin : Form
    {
        #region 变量
        /// <summary>
        /// 使用线程控制
        /// </summary>
        private bool IsUseThread_Listener = true;
        /// <summary>
        /// TCP客户端
        /// </summary>

        TCPHelper _TCPHelper = new TCPHelper();
        ///// <summary>
        ///// 线程监听用TcpListener
        ///// </summary>

        //TcpListener _listenter = null;

        ///// <summary>
        ///// 监听线程
        ///// </summary>
        //Thread thListener = null;
        #endregion 变量

        public TCPWin()
        {
            InitializeComponent();
        }

        private void TCPWin_Load(object sender, EventArgs e)
        {

        }

        ///// <summary>
        ///// 连接/修改连接
        ///// </summary>
        //private void btnModify_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        // 检查地址
        //        if (!CheckServerUrl())
        //        {
        //            return;
        //        }

        //        string hostname = txtIPAddress.Text;
        //        int port = int.Parse(txtPort.Text);
        //        bool result = _TCPHelper.TcpClient_Connect(hostname, port);  // 

        //        if (_TCPHelper.TcpClient_Connected)  // 需要连接时
        //        {
        //            if (result)
        //            {
        //                ShowLog("连接TCP服务器成功！");
        //                btnModify.BackColor = Color.FromArgb(128, 255, 128);
        //                btnModify.Text = "断开连接";
        //            }
        //            else
        //            {
        //                ShowLog("连接TCP服务器失败！");
        //                btnModify.BackColor = Color.FromArgb(255, 128, 128);
        //                btnModify.Text = "连接";
        //            }
        //        }
        //        else  // 需要断开连接时
        //        {
        //            _TCPHelper.TcpClient_Close();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ShowLog("连接TCP服务器，错误信息：" + ex.Message);
        //    }
        //}

        /// <summary>
        /// 开启/关闭监听-控制线程
        /// </summary>
        private void btnOpenCloseThread_Click(object sender, EventArgs e)
        {
            try
            {
                #region net FrameWork实现
                //if (btnOpenCloseThread.Text == "开启监听-控制线程")  // 开启监听
                //{
                //    // 检查地址
                //    if (!CheckServerUrl())
                //    {
                //        return;
                //    }
                //    IPHostEntry ipInfo = Dns.Resolve("127.0.0.1");  // 主机信息
                //    IPAddress[] ipList = ipInfo.AddressList;        // IP数组
                //    IPAddress localAddr = ipList[0];                // IP

                //    int port = int.Parse(txtPort.Text);
                //    _listenter = _TCPHelper.TcpListener_Start(localAddr, port);
                //    _listenter.Start(); // 开始监听

                //    thListener = new Thread(new ThreadStart(Run)); //定义线程进行监听
                //    thListener.IsBackground = true;
                //    thListener.Start(); //线程启动

                //    btnOpenCloseThread.Text = "关闭监听-控制线程";
                //    btnOpenCloseThread.BackColor = Color.FromArgb(128, 255, 128);
                //}
                //else  // 关闭监听
                //{
                //    if (thListener != null)
                //    {
                //        //thListener.Interrupt();
                //         _listenter.Stop();
                //    }

                //    btnOpenCloseThread.Text = "开启监听-控制线程";
                //    btnOpenCloseThread.BackColor = Color.FromArgb(255, 128, 128);
                //}
                #endregion net FrameWork实现

                #region Net5

                if (btnOpenCloseThread.Text == "开启监听-控制线程")  // 开启监听
                {
                    // 检查地址
                    if (!CheckServerUrl())
                    {
                        return;
                    }
                    IPHostEntry ipInfo = Dns.Resolve("127.0.0.1");  // 主机信息
                    var ipList = ipInfo.AddressList;                // IP数组
                    IPAddress localAddr = ipList[0];                // IP

                    int port = int.Parse(txtPort.Text);

                    Action<ResultData_TCP>? callback = TcpListener_ResultData_TCPHandle;

                    localAddr = null;
                    _TCPHelper.TcpListener_Start(localAddr, port, callback);

                    btnOpenCloseThread.Text = "关闭监听-控制线程";
                    btnOpenCloseThread.BackColor = Color.FromArgb(128, 255, 128);
                }
                else  // 关闭监听
                {
                    _TCPHelper.TcpListener_Stop();

                    btnOpenCloseThread.Text = "开启监听-控制线程";
                    btnOpenCloseThread.BackColor = Color.FromArgb(255, 128, 128);
                }
                #endregion Net5
            }
            catch (Exception ex)
            {
                btnOpenCloseThread.Text = "开启监听-控制线程";
                btnOpenCloseThread.BackColor = Color.FromArgb(255, 128, 128);

                ShowLog($"开启/关闭监听失败，错误信息: {ex.Message}");
            }
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查地址
                if (!CheckServerUrl())
                {
                    return;
                }

                string hostname = txtIPAddress.Text;
                int port = int.Parse(txtPort.Text);
                string sendMsg = txtMsg.Text;  // 
                if (string.IsNullOrEmpty(sendMsg))
                {
                    ShowLog("发送信息不可为空！");
                    return;
                }
                ResultData_TCP resultData_TCP = _TCPHelper.ConnectAndSendMsg_Nohandle(hostname, port, sendMsg);  // 连接并发送

                ShowLog(string.Concat("\r\n发送信息:内容：", sendMsg, "；结果：", resultData_TCP.ResultCode, "_", resultData_TCP.ResultMsg));
            }
            catch (Exception ex)
            {
                ShowLog("发送信息错误，错误信息：" + ex.Message);
            }
        }

        #region 方法

        ///// <summary>
        ///// 监听-线程方法
        ///// </summary>
        //private void Run()
        //{
        //    while (true)
        //    {
        //        try
        //        {
        //            using TcpClient client = _listenter.AcceptTcpClient();  // 接受一个Client
        //            NetworkStream stream = client.GetStream();              // 获取网络流

        //            // 接收信息
        //            byte[] buffer = new byte[client.ReceiveBufferSize];  // 存储接收到的流
        //            stream.Read(buffer, 0, buffer.Length);               // 读取网络流中的数据
        //            string dataStr = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length);
        //            Console.WriteLine("Received: {0}", dataStr);

        //            // 发回回复
        //            byte[] msg = System.Text.Encoding.ASCII.GetBytes(dataStr);
        //            stream.Write(msg, 0, msg.Length);
        //            string msgStr = System.Text.Encoding.ASCII.GetString(msg, 0, msg.Length);
        //            Console.WriteLine("Sent: {0}", msgStr);

        //            stream.Close();  // 关闭流
        //            client.Close();  // 关闭Client

        //            if (string.IsNullOrEmpty(dataStr))  // 展示
        //            {
        //                this.Invoke(new Action(() =>
        //                {
        //                    txtInfo.Text += string.Concat("\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "->", "线程监听_接收到内容，内容为：", dataStr);
        //                }));
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            this.Invoke(new Action(() =>
        //            {
        //                txtInfo.Text += string.Concat("\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "->", "线程监听出错，错误信息：", ex.Message);
        //            }));
        //        }
        //        Thread.Sleep(500);
        //    }
        //}

        /// <summary>
        /// TcpListener接收信息后的处理
        /// </summary>
        /// <param name="resultData_TCP"></param>
        private void TcpListener_ResultData_TCPHandle(ResultData_TCP resultData_TCP)
        {
            this.Invoke(new Action(() =>
            {
                txtInfo.Text += string.Concat("\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "->", " ResultCode：", resultData_TCP.ResultCode, "；ResultMsg：", resultData_TCP.ResultMsg, "接收信息：", resultData_TCP.ResultObject1, "；返回信息：", resultData_TCP.ResultObject2);
            }));
        }

        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="msg">信息</param>
        public void ShowLog(string msg)
        {
            txtInfo.Text += string.Concat("\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "->", msg);
        }

        /// <summary>
        /// 检查连接是否正常
        /// </summary>
        /// <returns>true为通过</returns>
        private bool CheckServerUrl()
        {
            if (string.IsNullOrEmpty(txtIPAddress.Text))  // 
            {
                ShowLog("发送信息不可为空！");
                return false;
            }
            if (string.IsNullOrEmpty(txtPort.Text))  // 
            {
                ShowLog("端口不可为空！");
                return false;
            }
            return true;
        }
        #endregion 方法
    }
}
